package scau.hotel.hotel_service.service.impl;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import scau.hotel.hotel_service.entity.*;
import scau.hotel.hotel_service.mapper.*;
import scau.hotel.hotel_service.service.CheckoutService;
import scau.hotel.hotel_service.vo.CheckoutVo;
import scau.hotel.hotel_model.controller.RespBean;
import scau.hotel.hotel_model.controller.RespBeanEnum;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * (Checkout)表服务实现类
 *
 * @author makejava
 * @since 2022-04-11 22:59:44
 */
@Service("checkoutService")
public class CheckoutServiceImpl implements CheckoutService {
    @Resource
    private CheckoutMapper checkoutMapper;

    @Resource
    private CheckinInforMapper checkinInforMapper;

    @Resource
    private PaymentMapper paymentMapper;

    @Resource
    private CheckinCusInforMapper checkinCusInforMapper;

    @Resource
    private RoomMapper roomMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param checkoutId 主键
     * @return 实例对象
     */
    @Override
    public Checkout queryById(Integer checkoutId) {
        return this.checkoutMapper.queryById(checkoutId);
    }

    /**
     * 分页查询
     *
     * @param checkout 筛选条件
     * @return 查询结果
     */
    @Override
    public List<Checkout> queryAll(Checkout checkout) {
        return this.checkoutMapper.queryAll(checkout);
    }

    /**
     * 分页查询
     *
     * @param checkout 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    @Override
    public Page<Checkout> queryByPage(Checkout checkout, PageRequest pageRequest) {
        long total = this.checkoutMapper.count(checkout);
        return new PageImpl<>(this.checkoutMapper.queryAllByLimit(checkout, pageRequest), pageRequest, total);
    }

    /**
     * 新增数据
     *
     * @param checkout 实例对象
     * @return 实例对象
     */
    @Override
    public RespBean insert(Checkout checkout) {
        this.checkoutMapper.insert(checkout);
        return RespBean.success();
    }

    /**
     * 修改数据
     *
     * @param checkout 实例对象
     * @return 实例对象
     */
    @Override
    public RespBean update(Checkout checkout) {
        this.checkoutMapper.update(checkout);
        return RespBean.success();
    }

    /**
     * 通过主键删除数据
     *
     * @param checkoutId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer checkoutId) {
        return this.checkoutMapper.deleteById(checkoutId) > 0;
    }

    /**
     * 查询提示今天即将退房或超时未退房的订单明细
     * @return
     */
    @Override
    public List<CheckinInfor> queryTodayCheckout(){
        Date date = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DAY_OF_MONTH, 1);
        try {
            date = sf.parse(sf.format(c.getTime()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return this.checkinInforMapper.queryTodayCheckout(date);
    }

    /**
     * 步骤 1
     * 返回退房房间的所有入住人以及押金总和
     * 需要参数为：入住明细id数组
     * @return RespBean
     */
    @Override
    public RespBean returnCheckoutCus(List<String> arrays){
        List<Integer> checkinInforIds = new ArrayList<>();
        for (String array : arrays) {
            Integer checkinInforId = Integer.valueOf(array);
            checkinInforIds.add(checkinInforId);
        }
        List<CheckinCusInfor> checkinCusInforList = new ArrayList<>();
        BigDecimal cashPledge = new BigDecimal("0");
        for (Integer checkinInforId : checkinInforIds) {
            List<CheckinCusInfor> cusInfors = this.checkinCusInforMapper.queryByCheckinInforId(checkinInforId);
            //为返回得到退房人姓名前附加入住明细id
            for(CheckinCusInfor checkinCusInfor:cusInfors){
                checkinCusInfor.setCheckinCusName(checkinInforId+checkinCusInfor.getCheckinCusName());
            }
            checkinCusInforList.addAll(cusInfors);
            if (this.paymentMapper.queryCashPledge(checkinInforId) != null) {
                cashPledge = cashPledge.add(this.paymentMapper.queryCashPledge(checkinInforId).getAmount());
            }
        }
        CheckoutVo checkoutVo = new CheckoutVo();
        checkoutVo.setCashPledge(cashPledge);
        checkoutVo.setCheckinCusInforList(checkinCusInforList);
        return RespBean.success(checkoutVo);
    }

    /**
     * 步骤 2
     * 确认退房
     * 需要参数：
     *     "checkinCusName": "string",
     *     "checkinId": 0,
     *     "checkinInforId": 0,
     *     "remark": "string"
     * @return RespBean
     */
    @Override
    public RespBean confirmCheckout(List<CheckoutVo> checkoutVoList) {
        //判断数组是否为空
        if (checkoutVoList == null) {
            return RespBean.error(RespBeanEnum.CHECKOUT_NULL_ERROR);
        } else {
            //获取CheckoutVo对象CheckinId属性，distinct()去重，count()获取去重后的集合数
            long count = checkoutVoList.stream().map(CheckoutVo::getCheckinId).distinct().count();
            //判断（如果全部相等：count应该等于1）
            if (count != 1) {
                return RespBean.error(RespBeanEnum.CHECKOUT_CHECKIN_ID_NOT_SAME_ERROR);
            } else {
                //获取传值类数据
                for (CheckoutVo checkoutVo : checkoutVoList) {
                    /* 退房表操作：新增数据 */
                    Checkout checkout = new Checkout();
                    //获取入住id
                    checkout.setCheckinId(checkoutVo.getCheckinId());
                    //获取入住明细id
                    checkout.setCheckinInforId(checkoutVo.getCheckinInforId());
                    //获取实际退房时间
                    checkout.setCheckoutDate(new Timestamp(System.currentTimeMillis()));
                    //获取退房人:去除姓名前的入住明细id
                    checkout.setCheckoutCusName(checkoutVo.getCheckinCusName().replaceAll("[^\\u4e00-\\u9fa5]", ""));
                    //获取备注
                    checkout.setRemark(checkoutVo.getRemark());
                    //设置状态：1代表已完成
                    checkout.setStatus(1);
                    //设置删除标志，1代表存在，0代表删除
                    checkout.setDelFlag(1);
                    //设置创建人
                    checkout.setCreatedBy("admin");
                    //设置数据创建时间
                    checkout.setCreateTime(new Timestamp(System.currentTimeMillis()));
                    //退房数据插入数据库
                    this.checkoutMapper.insert(checkout);

                    /* 入住明细表操作：更新入住明细状态 */
                    CheckinInfor checkinInfor = new CheckinInfor();
                    //获取入住明细id
                    checkinInfor.setCheckinInforId(checkoutVo.getCheckinInforId());
                    //修改对应入住明细的状态
                    checkinInfor.setStatus("已退房");
                    //更新状态
                    this.checkinInforMapper.update(checkinInfor);

                    /* 支付表操作：更新对应押金状态 */
                    if (this.paymentMapper.queryCashPledge(checkoutVo.getCheckinInforId()) != null) {
                        Payment payment = this.paymentMapper.queryCashPledge(checkoutVo.getCheckinInforId());
                        payment.setStatus("已退还");
                        //更新状态
                        this.paymentMapper.update(payment);
                    }

                    /* 房间表操作：更新房间状态 */
                    Room room = this.roomMapper.queryById(this.checkinInforMapper.queryById(checkoutVo.getCheckinInforId()).getRoomId());
                    room.setRoomState("空闲");
                    //更新状态
                    this.roomMapper.update(room);
                }
            }
            return RespBean.success();
        }
    }
}
